from rest_framework.decorators import action
from rest_framework.generics import ListAPIView
from rest_framework.response import Response
from rest_framework.viewsets import ReadOnlyModelViewSet

from apps.recruit.serializer import CitySerializer, EnterpriseSerializer, EnterpriseDetailSerializer, \
    RecruitDetailSerializer, RecruitSerializer
from .models import City, Enterprise, Recruit


class CityView(ListAPIView):
    queryset = City.objects.filter(ishot=1)
    serializer_class = CitySerializer


class EnterpriseHotListView(ListAPIView):
    queryset = Enterprise.objects.order_by('-visits')[:3]
    serializer_class = EnterpriseSerializer


class EnterpriseDetailViewSet(ReadOnlyModelViewSet):
    queryset = Enterprise.objects.all()
    serializer_class = EnterpriseDetailSerializer

    def list(self, request, *args, **kwargs):
        return Response('403', status=403)

    # 增加企业访问次数
    @action(methods=['put'], detail=True)
    def visit(self, request, pk):
        instance = self.get_object()
        instance.visits += 1
        instance.save()
        data = {"message": "更新成功", "success": True}
        return Response(data, status=201)

    # 收藏企业
    @action(methods=['post'], detail=True)
    def collect(self, request, pk):
        user = self.request.user
        # print(user)
        if user.is_authenticated:
            enterprise = self.get_object()
            # 多对多 增加
            enterprise.users.add(user)
            enterprise.save()
        else:
            return Response({'success': False, 'message': '未登录'}, status=400)
        data = {"message": "收藏成功", "success": True}
        return Response(data, status=201)


class RecruitDetailViewSet(ReadOnlyModelViewSet):
    queryset = Recruit.objects.order_by('-createtime')
    serializer_class = RecruitDetailSerializer

    def list(self, request, *args, **kwargs):
        return Response('403', status=403)

    # 增加职位访问次数
    @action(methods=['put'], detail=True)
    def visit(self, request, pk):
        instance = self.get_object()
        instance.visits += 1
        instance.save()
        data = {"message": "更新成功", "success": True}
        return Response(data, status=201)

    # 收藏职位
    @action(methods=['post'], detail=True)
    def collect(self, request, pk):
        user = self.request.user
        # print(user)
        if user.is_authenticated:
            recruit = self.get_object()
            # 多对多 增加
            recruit.users.add(user)
            recruit.save()
        else:
            return Response({'success': False, 'message': '未登录'}, status=400)
        data = {"message": "收藏成功", "success": True}
        return Response(data, status=201)

    # 最新的4个职位 recruits/search/latest/
    @action(methods=["GET"], detail=False, url_path="search/latest")
    def get_latest_job(self, request):
        jobs = self.get_queryset()[0:4]
        serializer = RecruitSerializer(instance=jobs, many=True)
        return Response(serializer.data)

    # 招聘首页获取推荐的4个职位 recruits/search/recommend/
    # 目前先简单实现,和最新职位的逻辑一致,后续再调整为推荐
    @action(methods=["GET"], detail=False, url_path="search/recommend")
    def get_recommend_job(self, request):
        jobs = self.get_queryset()[0:4]
        serializer = RecruitSerializer(instance=jobs, many=True)
        return Response(serializer.data)

    # 根据城市名称和关键字搜索职位 recruits/search/city/keyword/
    @action(methods=["POST"], detail=False, url_path="search/city/keyword")
    def search_job(self, request):
        cityname = request.data.get('cityname')
        keyword = request.data.get('keyword')
        jobs = self.get_queryset()
        ret_jobs = []
        if not cityname and not keyword:
            ret_jobs = jobs
        elif cityname and not keyword:
            for job in jobs:
                if job.city == cityname:
                    ret_jobs.append(job)
        elif not cityname and keyword:
            for job in jobs:
                if job.jobname.lower().find(keyword.lower()) != -1:
                    ret_jobs.append(job)
        else:
            for job in jobs:
                if job.city == cityname and job.jobname.lower().find(keyword.lower()) != -1:
                    ret_jobs.append(job)

        serializer = RecruitSerializer(instance=ret_jobs, many=True)
        return Response(serializer.data)
